import { lazyReportBatch } from "../report";
import { generateUniqueId } from "../utils";
// 导出一个默认函数，用于页面变化
export default function pageChange() {
  // hash histroy
  let oldUrl = "";
  // 监听hashchange事件
  window.addEventListener(
    "hashchange",
    function (event) {
      console.error("hashchange", event);
      // 获取新URL
      const newUrl = event.newURL;
      // 构造上报数据
      const reportData = {
        form: oldUrl,
        to: newUrl,
        type: "behavior",
        subType: "hashchange",
        startTime: performance.now(),
        uuid: generateUniqueId(),
      };
      // 调用懒加载上报函数
      lazyReportBatch(reportData);
      // 更新旧URL
      oldUrl = newUrl;
    },
    true
  );

  let from = "";
  // 监听popstate事件
  window.addEventListener(
    "popstate",
    function (event) {
      console.error("popstate", event);
      // 获取当前URL
      const to = window.location.href;
      // 构造上报数据
      const reportData = {
        form: from,
        to: to,
        type: "behavior",
        subType: "popstate",
        startTime: performance.now(),
        uuid: generateUniqueId(),
      };
      // 调用懒加载上报函数
      lazyReportBatch(reportData);
      // 更新from
      from = to;
    },
    true
  );
}
